<?php
namespace app\api\controller;

use app\api\Base;
use think\Config;
use think\Db;
class Admintag extends Base
{
    /**
     * 本接口共涵4个接口 题库标签 试题标签
     * 获取试题标签列表
     */
    public function getQuestionTag(){
    	$msg = ['code'=>400,'msg'=>'获取标签失败', 'data'=>[]];
    	# 接口一 直接获取题库标签列表
    	$plaformId = $this->request->param('plaformId') ? $this->request->param("plaformId"):0;
    	$admin_reg = $this->request->param('reg') ? $this->request->param('reg'):"";
    	$type = $this->request->param('type') ? $this->request->param('type'):0; # #接口二 获取试题标签列表0为题库标签 1为试题标签

    	#接口三 列表了那些标签 type =0 type=1
    	$selectId = $this->request->param("selectId")?$this->request->param("selectId"):"";  # 1,2,3选择中的标签 接口一 

    	// 接口一题库tag plaformId admin_reg type=0  列表没有选中状态 添加
    	// 接口二试题tag plaformId admin_reg type=1  列表没有选中状态 添加
    	// 接口三题库子列表选中状态 plaformId admin_reg type=0 selectId="1,2,3" 选中的子列表
    	// 接口四试题子列表选中状态 plaformId admin_reg type=0 selectId="1,2,3" 选中的子列表

    	try{
    		$where['isdelete'] = 0;
    		$where['status'] = 1;
    		$where['type'] = $type; # 0为题库标签 1为试题标签
    		$list = Db::name('qbankTag')->where($where)->field('id,pid,tagName')->select();
    		if($list){
    			$pList = []; #标签父亲级别列表
    			$childList = []; # val儿子标签
    			$selectList = []; # 选中标签
    			if($selectId){
    				$selectStr = explode(',',$selectId);	
    			}
    			for($i=0; $i<count($list); $i++){
    				if($list[$i]['pid']==0){
    					$pList[] = ['id'=>$list[$i]['id'] ,'name'=>$list[$i]['tagName'],'pid'=>$list[$i]['pid']];
    				}else{
    					//$childList[] = ['id'=>$list[$i]['id'] ,'name'=>$list[$i]['tagName'],'pid'=>$list[$i]['pid']];
    				}
    				if(in_array($list[$i]['id'],$selectStr)){
    					$selectList[] = ['id'=>$list[$i]['id'] ,'name'=>$list[$i]['tagName'],'pid'=>$list[$i]['pid']];
    				}
    				if(in_array($list[$i]['pid'],$selectStr)){
    					$childList[] = ['id'=>$list[$i]['id'] ,'name'=>$list[$i]['tagName'],'pid'=>$list[$i]['pid']];
    				}
    			}

    			# 返回数据
    			$msg['code'] = 200;
    			$msg['msg'] = "获取成功";
    			if($selectId){
    				$msg['data'] = ['tag'=>$selectList,'tagSelect'=>$childList];
    			}else{
    				$msg['data'] = $pList;
    			}
    		 	
    		}
    		
    	}catch(Exception $e){
    		$msg['msg'] = $e->getMessage();
    	}
    	return json_encode($msg);
    }
    /**
     * 题库试题标签详情 
     * 包含两个接口
     */
    public function tagInfo(){
        $msg = ['code'=>400, 'msg'=>'获取失败', 'data'=>[]];
        $palformId = $this->request->param("plaformId") ? $this->request->param("plaformId") : 0;
        $admin_reg = $this->request->param("admin_reg") ? $this->request->param("admin_reg"): ""; 
        $tagPid = $this->request->param("tagPid") ? $this->request->param("tagPid"): "";

        if(empty($tagPid)){
            $msg['msg'] = "请带入正确的标签标识";
            return json_encode($msg);
        }
        try{
            $where['isdelete'] = 0;
            $where['status'] = 1; 
            $where['_string'] ="pid=".$tagPid." or id=".$tagPid;  
            $tag = Db::name('qbank_tag')->query('select * from agk_qbank_tag where isdelete=0 and status=1 and (pid='.$tagPid.' or id='.$tagPid.')'); 
            if($tag){
                $tagParent = [];
                $tagChild = [];
                for($i=0; $i<count($tag); $i++){
                    if($tag[$i]['pid']==$tagPid){
                        $tagChild[] = ['id'=>$tag[$i]['id'],'name'=>$tag[$i]['tagName'],'pid'=>$tag[$i]['pid']];
                    }
                    if($tag[$i]['id']==$tagPid){
                        $tagParent = ['id'=>$tag[$i]['id'],'name'=>$tag[$i]['tagName'],'pid'=>$tag[$i]['pid']];
                    }
                }
                $msg['code'] = 200;
                $msg['msg'] = "获取成功";
                $msg['data '] = ['tag'=>$tagParent, 'tagSelect'=>$tagChild];
            }

        }catch(Exception $e){
            $msg['msg'] = $e->getMessage();
        }
        return json_encode($msg);
    }

    /**
     * 修改题库标签 试题标签 包含两个接口 type区分
     * 前端给我的一定是一个数组
     */
    public function editTag(){
        $msg = ['code'=>400, 'msg'=>'获取失败', 'data'=>[]];
        $palformId = $this->request->param("plaformId") ? $this->request->param("plaformId") : 0;
        $admin_reg = $this->request->param("admin_reg") ? $this->request->param("admin_reg"): ""; 
        $type = $this->request->param('type') ? $this->request->param('type'):0; # 如果不传默认修改题mu标签
        $tagPid = $this->request->param("tagPid") ? $this->request->param("tagPid"): ""; # 父亲级id
        $tagName = $this->request->param("tagName") ? $this->request->param("tagName") : ""; # 父亲标签名称
        //$selectList = $this->request->param("tagSelect") ? $this->request->param("tagSelect") : ""; # 字标签数组 为['id'=>id,'val'=>val] 如果id为则为新添加的 
        // $selectList = [
        //     ['id'=>1034,'tagName'=>'测试修改11'],
        //     ['id'=>1035,'tagName'=>'测试修改2111'],
        //     ['id'=>0,'tagName'=>'测试修改411'],
        // ];
        // $arr = array(
        //     'admin_reg'=>'admin_reg',
        //     'plaformId'=>0,
        //     'tagName'=>$tagName,
        //     'tagPid'=>$tagPid,
        //     'type'=>1,
        //     'tagSelect'=>$selectList,
        // );
        // return json_encode($arr);
        $postData = $this->request->post();
        $selectList = $postData['tagSelect'];
        if(empty($tagPid)){
            $msg['msg'] = "请带入标签ID";  
            return json_encode($msg);
        }
        if(empty($tagName)){
            $msg['msg'] = "请输入标签值";
            return json_encode($msg);
        }
        if(!is_array($selectList)){
            $msg['msg'] = "请带入正确的选项值";
            return json_encode($msg);
        }
        # 不允许重复的标签
        if($tagName){
            $wheres['id'] = ['neq',$tagPid];
            $wheres['tagName'] = $tagName; 
            $wheres['type'] = $type;
            $extName = Db::name('qbank_tag')->where($wheres)->field("id")->find();
            if($extName){
                $msg['msg'] = "已存在该标签，请勿重复添加";
                return json_encode($msg);
            }
        }

        try{
            $tagModel = Db::name('qbank_tag');

            # 得到所有的字标签选项
            $allChildTag = $tagModel->where(['pid'=>$tagPid,'isdelete'=>0])->field('id')->select(); 
            $childTagId = [];
            foreach ($allChildTag as $key => $value) { 
                $childTagId[] = $value['id'];
            }

            # 遍历得到要 
            $deleteArrayId = []; # 要删除id
            for($j=0; $j<count($selectList); $j++){
                # 添加新增的
                if($selectList[$j]['id']==0){
                    $addSelectData = ['pid'=>$tagPid,'tagName'=>$selectList[$j]['tagName'],'status'=>1,'plaformId'=>$plaformId,'type'=>$type,'admin_reg'=>$admin_reg,'isdelete'=>0,'createTime'=>time(), 'updateTime'=>time()];
                    $deleteArrayId[] = $tagModel->insertGetId($addSelectData);
                    
                }else{
                    # 修改
                    $updateSelect = ['tagName'=>$selectList[$j]['tagName'],'updateTime'=>time()];
                    $tagModel->where(['id'=>$selectList[$j]['id']])->update($updateSelect); 
                    $deleteArrayId[] = $selectList[$j]['id'];
                }
            }
            if($deleteArrayId){
                $delWhere['id'] =  ['not in',$deleteArrayId];
                $delWhere['pid'] = $tagPid;
            }else{
                $delWhere['pid'] = $tagPid;
            }
            $delSelect = $tagModel->where($delWhere)->setField(['isdelete'=>1]);
            $updatePidTagName = $tagModel->where(['id'=>$tagPid])->setField(['tagName'=>$tagName]);
            $msg['msg'] = '修改成功';
            $msg['code'] = 200;
        }catch(Exception $e){
            $msg['msg'] = $e->getMessage();
        }
        return json_encode($msg);
    }
    /**
     * 删除标签 删除标签和子类标签
     * 包含四个接口 列表 子标签 
     */
    public function deleteTag(){
        $msg = ['code'=>400,'msg'=>'删除失败','data'=>[]];
        $plaformId = $this->request->param("plaformId") ? $this->request->param("plaformId"):"";
        $admin_reg = $this->request->param("admin_reg") ? $this->request->param("admin_reg"): "";
        $id = $this->request->param("id") ?  $this->request->param("id") : "";
        if(empty($id)){
            $msg['msg'] = "请带入需要删除的标签";
            return json_encode($msg);
        }

        try{
            $tagModel = Db::name("qbank_tag");
            $where['isdelete'] = 0;
            $where['status'] = 1;
            $where['id'] = $id;
            $extes = $tagModel->where($where)->field("id,pid")->select();
            if($extes){
                if($extes[0]['pid']==0){
                    $ret = $tagModel->query("update agk_qbank_tag set isdelete=1 where id=".$id." or pid=".$id);
                }else{
                    $ret = $tagModel->query("update agk_qbank_tag set isdelete=1 where id=".$id);
                }
                $msg['code'] = 200;
                $msg['msg'] = "删除成功";
            }else{
                $msg['msg'] = "该标签已被删除，请勿重复删除";
                return json_encode($msg);
            }

        }catch(Exception $e){
            $msg['msg'] = $e->getMessage();
        }
        return json_encode($msg);
    }
    /**
     * 添加标签
     * type 0 题库 type 1试题
     */
    
    public function addTag(){
        $msg = ['code'=>400,'msg'=>'添加失败','data'=>[]];
        $plaformId = $this->request->param("plaformId") ? $this->request->param("plaformId"):"0";
        $admin_reg = $this->request->param("admin_reg") ? $this->request->param("admin_reg"): "";
        $type = $this->request->param("type") ? $this->request->param("type"): 0;
        $tag = $this->request->param("tag") ? $this->request->param("tag"): "";
        //$tagSelect = $this->request->param("tagSelect") ? $this->request->param("tagSelect") : "";//array('ceshi','测试张集散');
        $postData = $this->request->post();
        $tagSelect = $postData['tagSelect'];
        if(empty($tag)){
            $msg['msg'] = "请填写标签值";
            return json_encode($msg);
        }
        if(!is_array($tagSelect)){
            $msg['msg'] = "标签选项应该为一个数组";
            return json_encode($msg);
        } 
        # 不允许重复的标签
        if($tag){
            $wheres['tagName'] = $tag; 
            $wheres['type'] = $type;
            $extName = Db::name('qbank_tag')->where($wheres)->field("id")->find();
            if($extName){
                $msg['msg'] = "已存在该标签，请勿重复添加";
                return json_encode($msg);
            }
        }
        try{
            # 插入标签值 
            $db = Db::name('qbank_tag');
            $pData = [
                'pid'=>0,
                'tagName'=>$tag,
                'type'=>$type,
                'plaformId'=>$plaformId,
                'status'=>1,
                'admin_reg'=>$admin_reg,
                'createTime'=>time(),
                'updateTime'=>time()
            ];
            $pid = $db->insertGetId($pData);
            if($pid){
                $cData = [];
                for ($i=0; $i <count($tagSelect) ; $i++) { 
                    $cData[] = ['pid'=>$pid, 'tagName'=>$tagSelect[$i],'type'=>$type,'status'=>1,'admin_reg'=>$admin_reg, 'createTime'=>time(), 'updateTime'=>time()];
                }
                $ret = $db->insertAll($cData);
                if($ret){
                    $msg['code']= 200;
                    $msg['msg'] = '添加成功';
                }
            }
        }catch(Exception $e){
            $msg['msg'] = $e->getMessage();
        }
        return json_encode($msg);
    }
}